<template>
  <div class="areaView">
    <h1 class="left-tit-more">
      <div class="tit">
        <span>来访地区</span>
      </div>
      <router-link to="/statistics/visit/area" class="more">更多></router-link>
    </h1>
    <div class="top-tool">
      <TypeSelect v-model:value="dateType" :typeList="dateTypeList" />
    </div>
    <div class="data-box" v-loading="chartLoading">
      <div ref="map" style="height: 350px; width: 70%"></div>
      <div class="rank-data">
        <RankCard :data="rankData"></RankCard>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive, watch, defineProps, computed } from 'vue'
import { getStationAreaData } from '@/api/log'
import { useStore } from 'vuex'
import { applyOpacityArray, getStartAndEndTimes } from '@/utils/tools'
import RankCard from './RankCard.vue'
import TypeSelect from './TypeSelect.vue'
import chinaMap from '@/assets/china.json'
import echarts from '@/utils/echarts'

const store = useStore()
const siteId = computed(() => store.state.site.currentSite?.id)
//5+版本中移除了echarts/map/china.js文件,需自己下载地图文件注册
echarts.registerMap('china', { geoJSON: chinaMap })
const props = defineProps({
  params: {
    type: Object,
    default: () => {}
  }
})

const chartLoading = ref(false)
const dateType = ref(0)
const dateTypeList = ref([
  { value: 0, label: '今日' },
  { value: 1, label: '昨日' },
  { value: 2, label: '近7日' },
  { value: 3, label: '近30日' }
])
//查询参数
let params = reactive({
  startTime: '',
  endTime: ''
})
const map = ref(null) //获取dom
// 获取数据
const allData = ref({
  mapData: [],
  rankData: []
})
const rankData = ref()
const getData = async () => {
  chartLoading.value = true
  params.siteId = siteId.value
  try {
    let res = await getStationAreaData(params)
    allData.value.mapData = res.data
    allData.value.rankData = res.data
  } catch {
    chartLoading.value = false
  }
  chartLoading.value = false
}
watch(
  allData,
  newVal => {
    option.series[0].data = newVal.mapData
    option.visualMap.pieces = getPieces()
    myChart.setOption(option)
    rankData.value = newVal.rankData.slice(0, 5)
  },
  { deep: true }
)
watch(
  props,
  newVal => {
    params.siteId = newVal.params.siteId
    getData()
  },
  { deep: true }
)
watch(
  dateType,
  () => {
    const { startTime, endTime } = getStartAndEndTimes(dateType.value, true)
    params.startTime = startTime
    params.endTime = endTime
    getData()
  },
  { immediate: true }
)
//获取地图颜色分段配置(分5段)
let themeColor = ref(getComputedStyle(document.documentElement).getPropertyValue(`--el-color-primary`))
let colorArr = applyOpacityArray(themeColor.value, [0.1, 0.3, 0.5, 0.7, 0.9])
const getPieces = () => {
  const maxValue = allData.value.mapData.reduce((prev, curr) => {
    return curr.value > prev ? curr.value : prev
  }, 0)
  const minValue = allData.value.mapData.reduce((min, current) => {
    if (current.value > 0 && current.value < min.value) {
      return current.value
    } else {
      return min
    }
  }, 1)
  let splitRange = Math.ceil((maxValue - minValue) / 5)
  let pieces = []
  for (var i = 0; i < 5; i++) {
    var startValue = minValue + splitRange * i
    var endValue = minValue + splitRange * (i + 1)
    pieces.push({
      min: startValue,
      max: endValue,
      color: colorArr[i]
    })
  }
  return pieces
}
//地图配置
const option = reactive({
  tooltip: {
    textStyle: {
      color: '#ffffff'
    },
    borderWidth: 0,
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    formatter: function (params) {
      if (params.name === '南海诸岛') {
        return // 不展示tooltip
      }
      if (params.data && params.data.value) {
        return params.name + '，点击数：' + params.data.value
      } else {
        return params.name
      }
    }
  },
  visualMap: {
    type: 'piecewise',
    seriesIndex: 0, // 需要关联的地图系列索引
    show: false,
    pieces: []
  },
  geo: {
    map: 'china',
    zoom: 1.1,
    top: 10,
    left: 30,
    label: {
      show: true,
      fontSize: '12',
      color: 'rgba(0,0,0,0.7)'
    },
    itemStyle: {
      borderColor: 'rgba(0, 0, 0, 0.2)'
    },
    emphasis: {
      itemStyle: {
        areaColor: themeColor.value
      }
    }
  },
  series: [
    {
      name: '',
      type: 'map',
      geoIndex: 0,
      silent: true,
      data: allData.value.mapData.map(item => {
        if (item.name === '南海诸岛') {
          item.silent = true
        }
        return item
      })
    }
  ]
})
//初始化地图
let myChart
onMounted(() => {
  params.siteId = props.siteId
  myChart = echarts.init(map.value)
  myChart.setOption(option)
  window.onresize = function () {
    myChart.resize()
  }
})
</script>

<style lang="scss" scoped>
.areaView {
  padding: 20px;
  background-color: $white;
  .left-tit-more {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    .tit {
      display: flex;
      align-items: center;
      font-size: 18px;
      color: #333333;
    }
    .more {
      font-size: 14px;
      color: #7f7f7f;
    }
  }
  .top-tool {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    height: 50px;
  }
  .data-box {
    display: flex;
    justify-content: space-between;
    .rank-data {
      flex: 1;
    }
  }
}
</style>
